<template>
  <div class="value-set-wrap">
    <Form :model="formSearch" :rules="rules" ref="vsForm" :label-width="95">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="vsiKey" :label="_$t('valuecode')">
            <Input type="text" v-model.trim="formSearch.vsiKey" :disabled="readOnly" />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="vsiValue" :label="_$t('value')">
            <LangInput v-model="formSearch.vsiValue" />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="_$t('parentValue')" prop="vsiParentKey">
            <Select v-model="formSearch.vsiParentKey" :disabled="noEdit">
              <Option
                v-for="item in parentValueList"
                :title="item.vsiValue"
                :value="item.vsiKey"
                :key="item.vsiKey"
              >{{ item.vsiValue }}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="tenantCode" :label="_$t('ownnerTenant')">
            <Input
              v-model="formSearch.tenantCode"
              :transfer="true"
              :disabled="tenantCode != null || vsId != ''"
              clearable
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="vsiStartDate" :label="_$t('startDate')">
            <DatePicker
              :transfer="true"
              type="date"
              ref="vsiStartDate"
              :placeholder="_$t('selectDate')"
              :value="formSearch.vsiStartDate"
              :editable="false"
              :clearable="false"
              :options="startDateOptions"
              @on-change="changeEffectBegin"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="vsiEndDate" :label="_$t('endDate')">
            <DatePicker
              :transfer="true"
              type="date"
              ref="vsiEndDate"
              :placeholder="_$t('effectiveTime')"
              :value="formSearch.vsiEndDate"
              :editable="false"
              :clearable="false"
              :options="endDateOptions"
              @on-change="changeEffectEnd"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="sort" :label="$t('common.sort')">
            <InputNumber :max="100"  :precision="0" :step="1" :min="0" v-model="formSearch.sort"></InputNumber>
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="formSearch.enabled">
              <Radio label="1">{{ this.$t("common.enable") }}</Radio>
              <Radio label="0">{{ this.$t("common.disable") }}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item :label="_$t('vsDesc')">
            <Input type="textarea" :rows="4" v-model="formSearch.vsiDescription"></Input>
          </Form-item>
        </Col>
      </Row>
    </Form>
    <!-- 拓展属性模板 -->
    <div v-if="!isShowTemplate" class="extendClass">
      <p class="extendedAttrTitle">{{ extendedAttrTitle }}</p>
      <span style="font-size: 14px; padding-right: 9px;">{{ $t("module.valueSet.template") }}</span>
      <Select
        @on-change="changeSelect"
        v-model="formSearch.attributeContext"
        class="no-borderColor"
        style="width: 40%;"
      >
        <Option
          v-for="(item, index) in valueSetTemplateList"
          :key="index"
          :value="item.id"
          :style="{ color: item.status == 2 ? '#bcbcbc!important' : '' }"
        >{{ item.templateName }}</Option>
        <!-- <Option v-for="(item,index) in valueSetTemplateList" :key="index" :value="item.id">
          <span :style="item.status == 2?'color:#bcbcbc':''">{{item.templateName}}</span>
        </Option>-->
      </Select>
      <div
        class="assign-tree-dimension"
        ref="treeRoot"
        v-if="formSearch.attributeContext && isHintShow"
      >
        <span
          class="operation-hint"
          style="margin-left: 0;"
        >{{ $t("module.treeManage.templateNull") }}</span>
      </div>
      <!-- 选择拓展属性模板 - 生成的表单 -->
      <form-create
        v-if="isShowForm"
        v-model="fcApi"
        :rule="ruleData"
        :option="option"
        class="extend-attr-create-formstyle"
      ></form-create>
    </div>
  </div>
</template>
<script>
import VsGlobal from "./VsGlobal.vue";
import valueSet from "@lang/modules/valueSet";
import tenantAPI from "@api/tenantApi.js";
import { getValueSetTemplateList, templateDetail } from "@/api/extendAttrApi.js";
import { codeReg } from "@/const.js";

// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  components: {},
  props: {
    type: {
      type: Number,
      default() {
        return 0;
      }
    },
    currentVsCode: {
      type: String,
      default() {
        return "";
      }
    },
    productCode: {
      type: String,
      default() {
        return "";
      }
    },
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    vsId: {
      type: String,
      default() {
        return "";
      }
    },
    vsType: {
      type: String,
      default() {
        return "";
      }
    },
    teantName: {
      type: String,
      default() {
        return "";
      }
    },
    rowList: {
      type: Object,
      default() {
        return {};
      }
    },
    attributeContext: {
      type: String,
      default() {
        return "";
      }
    },
    vsParentCode: {
      type: String,
      default() {
        return "";
      }
    }
  },
  locales: {
    "zh-CN": {
      module: {
        valueSet: valueSet["zh-CN"]
      }
    },
    "en-US": {
      module: {
        valueSet: valueSet["en-US"]
      }
    }
  },
  data() {
    const validateVsCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this._$t("enterVCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const errorMessageValidater = (rule, value, callback) => {
      let flag = value.filter(item => {
        if (item.value == "") {
          return true;
        }
      });
      if (flag.length > 0 || value.length == 0) {
        callback(new Error(this._$t("enterVName")));
      } else {
        callback();
      }
    };
    return {
      vsiParentKey: "",
      tenantList: [],
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          // icon: "add",
          handle: this.save,
          loading: false
        },
        {
          text: this.$t("common.close"),
          // theme: "primary",
          handle: () => {
            this.$emit("Close");
          }
        }
      ],
      formSearch: {
        tenantCode: null,
        vsiKey: "",
        // vsiValue: this.rowList.vsiValue,
        vsiValue: [],
        vsiStartDate: "",
        vsiEndDate: "",
        enabled: "1",
        owner: "",
        sort: 0,
        vsiDescription: "",
        attributeContext: "",
        vsiParentKey: ""
      },
      parentValueList: [],
      valueSetTemplateList: [],
      version: "",
      isShow: false,
      noEdit: false,
      readOnly: false,
      ruleList: [],
      isShowForm: false,
      isHintShow: false,
      isShowTemplate: false,
      fcApi: null,
      rules: {
        vsiKey: [{ validator: validateVsCode, trigger: "blur", required: true }],
        vsiParentKey: this.type == 2 ? [{ required: true, message: this._$t("selectParentVs") }] : [],
        vsiValue: [{ required: true, validator: errorMessageValidater, trigger: "change" }],
        tenantCode: [{ required: true, message: this._$t("enterTenant"), trigger: "blur" }],
        sort: [{ required: true, type: "number", message: this._$t("enterSort"), trigger: "change" }],
        vsiStartDate: [{ required: true, type: "string", trigger: "change" }],
        vsiEndDate: [{ required: true, type: "string", trigger: "change" }]
      }
    };
  },
  computed: {
    extendedAttrTitle: function() {
      return this.$t("module.valueSet.extendedAttr");
    },
    ruleData() {
      return this.ruleList;
    },
    option() {
      return {
        resetBtn: false,
        submitBtn: false,
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    },
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.formSearch.vsiEndDate == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.formSearch.vsiEndDate.valueOf() - ONE_DAY
            );
          } else if (typeof _this.formSearch.vsiEndDate == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.formSearch.vsiEndDate.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.formSearch.vsiStartDate == "object") {
            // 生效日期是日期对象，如 new Date()
            return date && date.valueOf() < _this.formSearch.vsiStartDate.valueOf() - ONE_DAY;
          } else if (typeof _this.formSearch.vsiStartDate == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            if (_this.formSearch.vsiStartDate == "") {
              return date && date.valueOf() < Date.now() - ONE_DAY;
            }
            let formatStr = _this.formSearch.vsiStartDate.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  created: function() {
    //这个还要多语言?
    if (this.vsType == this._$t("independent")) {
      this.noEdit = true;
    }
    //获取父值下拉列表
    // $http.get(`${window.RPConfig.setting}/valueset/item/list/parent?vsCode=` + this.currentVsCode).then(response => {
    $http.get(`${window.RPConfig.setting}/valueset/item/list?vsCode=` + this.vsParentCode).then(response => {
      for (const key in response.data) {
        if (response.data.hasOwnProperty(key)) {
          this.parentValueList.push({
            vsiKey: response.data[key].vsiKey,
            vsiValue: response.data[key].vsiValue
          });
        }
      }
    });
    this.initTenant();
    if (this.vsId) {
      this.isShow = true;
      this.noEdit = true;
      this.readOnly = true;
      this.$emit("SetTitle", this._$t("editVc"));
      this.formSearch.vsiKey = this.rowList.vsiKey;
      this.formSearch.vsiValue = this.rowList.vsiValue;
      this.formSearch.vsiStartDate = this.formatDateTime(this.rowList.vsiStartDate);
      this.formSearch.vsiEndDate = this.rowList.vsiEndDate == null ? "" : this.formatDateTime(this.rowList.vsiEndDate);
      this.formSearch.enabled = String(this.rowList.enabled);
      this.formSearch.vsiParentKey = this.rowList.vsiParentKey;
      this.version = this.rowList.version;
      this.formSearch.tenantCode = this.rowList.tenantName || null;
      this.formSearch.sort = +this.rowList.sort;
      this.formSearch.vsiDescription = this.rowList.vsiDescription;
      this.formSearch.attributeContext = this.rowList.attributeContext; // 扩展属性模板
      this.ruleList = this.rowList.attributeValue ? this.rowList.attributeValue.template : [];
      // 取到模板数据便渲染表单组件
      this.isShowForm = true;
    } else {
      this.$emit("SetTitle", this._$t("createVc"));
      this.formSearch.vsiStartDate = new Date()
        .toISOString()
        .replace(/T.*/, " ")
        .trim();
      this.formSearch.vsiEndDate = "2099-12-31";
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
    this.getValueSetTemplate([1]);
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    _$t(key) {
      return this.$t(`module.valueSet.${key}`);
    },
    save() {
      this.$refs["vsForm"].validate(valid => {
        if (valid) {
          debugger
          const newFormData = {};
          if (this?.fcApi?.formData) {
            const formData = this.fcApi.formData();
            const rules = this.fcApi.rule;
            for (const r of rules) {
              newFormData[r.matchColumn] = r.type === 'checkbox'
                ? JSON.stringify(formData[r.field])
                : formData[r.field];
            }
          }
          this.actions[0].loading = true;
          const formInfo = {
            sort: this.formSearch.sort,
            vsCode: this.currentVsCode,
            vsiKey: this.formSearch.vsiKey,
            valueSetItemLangVos: this.formSearch.vsiValue,
            enabled: this.formSearch.enabled,
            vsiStartDate: this.formSearch.vsiStartDate,
            vsiEndDate: this.formSearch.vsiEndDate,
            tenantCode: this.tenantCode,
            vsiParentKey: this.formSearch.vsiParentKey,
            vsiDescription: this.formSearch.vsiDescription,
            attributeContext: this.formSearch.attributeContext, // 扩展属性模板
            attributeValue: {
              template: this.ruleData
            },
            ...newFormData
          };
          //通过vsId判断save方法是添加还是编辑操作
          if (this.vsId) {
            $http
              .post(`${window.RPConfig.setting}/valueset/item/update`, {
                version: this.version,
                id: this.vsId,
                ...formInfo
              })
              .then(() => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this._$t("updateSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(error => {
                this.actions[0].loading = false;
              });
          } else {
            $http
              .post(`${window.RPConfig.setting}/valueset/item/add`, formInfo)
              .then(() => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this._$t("createSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(error => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error({
            content: this._$t("formValidateFailed"),
            duration: 3
          });
        }
      });
    },
    cancel() {
      this.$emit("Close");
    },
    // 获取公司模板数据
    getValueSetTemplate(statusList) {
      getValueSetTemplateList(statusList).then(res => {
        if (res.data.length == 0) {
          this.isShowTemplate = true;
          return;
        } else {
          this.isShowTemplate = false;
        }
        this.valueSetTemplateList = res.data;
        // 获取已归档模板（意义相当于选择以后被无效的模板）
        this.templateDetail(this.attributeContext, "pigeonhole");
      });
    },
    // // 切换模板
    // changeSelect(val) {
    //   templateDetail(val).then(res => {
    //     this.ruleList = res.data.attributeContent.template;
    //     this.isShowForm = true;
    //   });
    // },
    // 切换模板
    changeSelect(val) {
      this.templateDetail(val, "changeSelect");
    },
    // 获取模板详情
    templateDetail(val, sign) {
      templateDetail(val).then(res => {
        if (sign == "pigeonhole") {
          const arr = [...this.valueSetTemplateList, res.data || {}];
          const obj = {};
          this.valueSetTemplateList = arr.filter(d => {
            if (d.id && !obj[d.id]) {
              obj[d.id] = true;
              return true;
            }
          });
          const templateList = res?.data?.attributeContent?.template || []
          const { rowList } = this
          this.ruleList = templateList.map(t => {
            const item = {
              ...t,
              value: t.type === 'checkbox' && t?.matchColumn
                ? rowList?.[t?.matchColumn]
                  ? JSON.parse(rowList?.[t?.matchColumn])
                  : []
                : rowList?.[t?.matchColumn] || ''
            }
            return item
          })
        } else {
          this.ruleList = res.data.attributeContent.template;
          this.isShowForm = true;
          this.isHintShow = this.ruleList.length == 0;
        }
      });
    },
    // nameEdit() {
    //   new this.$pageModal(
    //     VsGlobal,
    //     {
    //       props: {
    //         vsiId: this.vsId
    //       }
    //     },
    //     data => {
    //       //编辑名称后刷新当前页面
    //       const langCode = window.localStorage.language || sessionStorage.LangCode;
    //       for (const key in data) {
    //         if (langCode == data[key].langCode) {
    //           this.formSearch.vsiValue = data[key].vsiValue; //编辑名称后刷新右侧功能详情
    //         }
    //       }
    //     }
    //   );
    // },
    changeEffectBegin(date) {
      // if (this.formSearch.vsiEndDate && date && new Date(date) > new Date(this.formSearch.vsiEndDate)) {
      //   this.formSearch.vsiStartDate = "";
      //   this.$refs["vsiStartDate"].handleClear();
      //   this.$message.error({
      //     content: this.$t("module.valueSet.warning.dateCompare"),
      //     duration: 3
      //   });
      //   return;
      // }
      this.formSearch.vsiStartDate = date;
    },
    clearEffectBegin() {
      this.formSearch.vsiStartDate = new Date();
    },
    changeEffectEnd(date) {
      // if (this.formSearch.vsiStartDate && date && new Date(date) < new Date(this.formSearch.vsiStartDate)) {
      //   this.formSearch.vsiEndDate = "";
      //   this.$refs["vsiEndDate"].handleClear();
      //   this.$message.error({
      //     content: this.$t("module.valueSet.warning.dataInvalid"),
      //     duration: 3
      //   });
      //   return;
      // }

      this.formSearch.vsiEndDate = date;
    },
    clearEffectEnd() {
      this.formSearch.vsiEndDate = "";
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      // var time = new Date(Date.parse(date));
      // time.setTime(time.setHours(time.getHours() + 8));
      // var Y = time.getFullYear() + "-";
      // var M = this.addZero(time.getMonth() + 1) + "-";
      // var D = this.addZero(time.getDate()) + " ";
      // var h = this.addZero(time.getHours()) + ":";
      // var m = this.addZero(time.getMinutes()) + ":";
      // var s = this.addZero(time.getSeconds());
      // return Y + M + D;
      // 解决IE不支持Data.parse()的问题
      return date
        ? new Date(
            date
              .replace(/-/g, "/")
              .replace("T", " ")
              .replace(".000+0000", "")
          ).Format("yyyy-MM-dd")
        : "";
    },
    getDateString(DateStr) {
      if (DateStr == undefined || DateStr == null || DateStr == "" || DateStr.trim() == "") {
        return "";
      }
      return DateStr.split(" ")[0];
    },
    // 初始化所属租户
    initTenant() {
      if (this.vsId) {
        tenantAPI.queryAllTenantList().then(data => {
          this.tenantList = data;
        });
      } else {
        tenantAPI.queryTenantList().then(data => {
          this.tenantList = data;
        });
      }
      // 新增时
      if (this.vsId == "" && this.teantName) {
        this.formSearch.tenantCode = this.teantName;
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
.extendedAttrTitle {
  font-size: 14px;
  font-weight: bold;
  border-bottom: 0 !important;
  line-height: 14px !important;
  margin-bottom: 20px;
}

.value-set-wrap {
  // 选择拓展属性模板生成的表单
  .ivu-input-number {
    width: 100%;
  }
  .extend-attr-create-formstyle {
    margin-top: 20px;
    padding: 0;
    .ivu-form-item {
      display: flex;
      justify-content: space-between;
      .ivu-form-item-label {
        width: auto !important;
        min-width: 69px !important;
        max-width: 188px !important;
      }
      .ivu-form-item-content {
        margin-left: 0 !important;
        flex: 1;
        .ivu-input-number {
          width: 100% !important;
        }
      }
    }
  }
  .extendClass {
    border: 1px solid #eee;
    padding: 20px;
    margin-left: 0 !important;
  }
}
</style>
